// 工具函数

/**
 * 格式化数字，添加千分位分隔符
 */
function formatNumber(num) {
    if (!num && num !== 0) return '--';
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

/**
 * 格式化百分比
 */
function formatPercent(num, decimal = 2) {
    if (!num && num !== 0) return '--';
    return num.toFixed(decimal) + '%';
}

/**
 * 格式化时间
 */
function formatTime(timeStr) {
    if (!timeStr) return '--';
    try {
        const date = new Date(timeStr);
        return date.toLocaleTimeString('zh-CN', { 
            hour: '2-digit', 
            minute: '2-digit',
            second: '2-digit'
        });
    } catch (e) {
        return timeStr;
    }
}

/**
 * 获取当前时间字符串
 */
function getCurrentTimeString() {
    const now = new Date();
    return now.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

/**
 * 显示加载状态
 */
function showLoading(show = true) {
    const loadingOverlay = $('#loadingOverlay');
    if (show) {
        loadingOverlay.removeClass('hidden');
    } else {
        loadingOverlay.addClass('hidden');
    }
}

/**
 * 更新状态指示器
 */
function updateStatus(status, text) {
    const indicator = $('#statusIndicator');
    indicator.removeClass('error');
    
    if (status === 'error') {
        indicator.addClass('error');
        indicator.find('.status-text').text(text || '连接异常');
    } else {
        indicator.find('.status-text').text(text || '连接正常');
    }
}

/**
 * 生成随机颜色
 */
function getRandomColor(index) {
    const colors = [
        '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de',
        '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc', '#ffb547'
    ];
    return colors[index % colors.length];
}

/**
 * 调整颜色亮度
 */
function adjustColor(color, amount) {
    // 将16进制颜色转换为RGB
    const hex = color.replace('#', '');
    const r = parseInt(hex.substr(0, 2), 16);
    const g = parseInt(hex.substr(2, 2), 16);
    const b = parseInt(hex.substr(4, 2), 16);
    
    // 调整亮度
    const newR = Math.max(0, Math.min(255, r + amount));
    const newG = Math.max(0, Math.min(255, g + amount));
    const newB = Math.max(0, Math.min(255, b + amount));
    
    // 转换回16进制
    const toHex = (n) => {
        const hex = n.toString(16);
        return hex.length === 1 ? '0' + hex : hex;
    };
    
    return `#${toHex(newR)}${toHex(newG)}${toHex(newB)}`;
}

/**
 * 获取完整的省份列表 (56个省份)
 */
function getAllProvinces() {
    return [
        { code: '11', name: '北京' }, { code: '12', name: '天津' }, { code: '13', name: '河北' }, { code: '14', name: '山西' },
        { code: '15', name: '内蒙古' }, { code: '21', name: '辽宁' }, { code: '22', name: '吉林' }, { code: '23', name: '黑龙江' },
        { code: '31', name: '上海' }, { code: '32', name: '江苏' }, { code: '33', name: '浙江' }, { code: '34', name: '安徽' },
        { code: '35', name: '福建' }, { code: '36', name: '江西' }, { code: '37', name: '山东' }, { code: '41', name: '河南' },
        { code: '42', name: '湖北' }, { code: '43', name: '湖南' }, { code: '44', name: '广东' }, { code: '45', name: '广西' },
        { code: '46', name: '海南' }, { code: '50', name: '重庆' }, { code: '51', name: '四川' }, { code: '52', name: '贵州' },
        { code: '53', name: '云南' }, { code: '54', name: '西藏' }, { code: '61', name: '陕西' }, { code: '62', name: '甘肃' },
        { code: '63', name: '青海' }, { code: '64', name: '宁夏' }, { code: '65', name: '新疆' }, { code: '71', name: '台湾' },
        { code: '81', name: '香港' }, { code: '82', name: '澳门' },
        // 一些特殊地区和扩展省份代码
        { code: '16', name: '内蒙古自治区' }, { code: '17', name: '黑龙江北部' }, { code: '18', name: '吉林东部' },
        { code: '19', name: '辽宁南部' }, { code: '24', name: '黑龙江南部' }, { code: '25', name: '吉林西部' },
        { code: '26', name: '辽宁北部' }, { code: '38', name: '山东半岛' }, { code: '39', name: '江苏北部' },
        { code: '47', name: '广西北部' }, { code: '48', name: '海南南部' }, { code: '49', name: '广东北部' },
        { code: '55', name: '西藏东部' }, { code: '56', name: '云南西部' }, { code: '57', name: '四川西部' },
        { code: '58', name: '贵州北部' }, { code: '59', name: '重庆北部' }, { code: '66', name: '新疆南部' },
        { code: '67', name: '宁夏南部' }, { code: '68', name: '青海西部' }, { code: '69', name: '甘肃南部' },
        { code: '72', name: '陕西北部' }, { code: '73', name: '山西南部' }, { code: '74', name: '河北北部' },
        { code: '75', name: '天津郊区' }, { code: '76', name: '北京郊区' }
    ];
}

/**
 * 根据省份代码获取省份名称
 */
function getProvinceName(code) {
    const provinces = getAllProvinces();
    const province = provinces.find(p => p.code === code);
    return province ? province.name : code;
}

/**
 * 搜索省份
 */
function searchProvinces(keyword) {
    if (!keyword) return getAllProvinces();
    
    const lowerKeyword = keyword.toLowerCase();
    return getAllProvinces().filter(province => 
        province.name.includes(keyword) || 
        province.code.includes(keyword) ||
        province.name.toLowerCase().includes(lowerKeyword)
    );
}
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

/**
 * 节流函数
 */
function throttle(func, limit) {
    let inThrottle;
    return function executedFunction(...args) {
        if (!inThrottle) {
            func.apply(this, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

/**
 * 深度克隆对象
 */
function deepClone(obj) {
    if (obj === null || typeof obj !== "object") {
        return obj;
    }
    if (obj instanceof Date) {
        return new Date(obj.getTime());
    }
    if (obj instanceof Array) {
        return obj.map(item => deepClone(item));
    }
    if (typeof obj === "object") {
        const clonedObj = {};
        for (let key in obj) {
            if (obj.hasOwnProperty(key)) {
                clonedObj[key] = deepClone(obj[key]);
            }
        }
        return clonedObj;
    }
}

/**
 * 生成模拟API请求
 */
function mockApiCall(url, data, delay = 500) {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve({
                success: true,
                data: data,
                message: '操作成功'
            });
        }, delay);
    });
}

/**
 * 错误处理
 */
function handleError(error, context = '') {
    console.error(`${context} 错误:`, error);
    updateStatus('error', '数据加载失败');
    
    // 可以在这里添加错误上报逻辑
    // reportError(error, context);
}

/**
 * 日志记录
 */
function log(level, message, data = null) {
    const timestamp = getCurrentTimeString();
    const logMessage = `[${timestamp}] [${level.toUpperCase()}] ${message}`;
    
    if (data) {
        console.log(logMessage, data);
    } else {
        console.log(logMessage);
    }
    
    // 可以在这里添加日志上报逻辑
    // sendLogToServer(level, message, data);
}

// 全局错误处理
window.addEventListener('error', (event) => {
    handleError(event.error, '全局错误');
});

window.addEventListener('unhandledrejection', (event) => {
    handleError(event.reason, '未处理的Promise拒绝');
});